package logic

import (
	"context"
	"encoding/json"
	"select/models/cache"
	"select/models/mysql"
	"time"

	"select/selectrpc/internal/svc"
	"select/selectrpc/selectrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShopListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShopListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShopListLogic {
	return &ShopListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ShopListLogic) ShopList(in *selectrpc.ShopListRequest) (*selectrpc.ShopListResponse, error) {
	// todo: add your logic here and delete this line

	var shop []mysql.ShopClassBrand
	result, _ := cache.Rdb.Get(l.ctx, "shopList").Result()
	if result == "" {

		mysql.DB.Debug().Find(&shop)

		marshal, _ := json.Marshal(shop)
		cache.Rdb.Set(l.ctx, "shopList", marshal, time.Hour*1)
	} else {
		json.Unmarshal([]byte(result), &shop)
	}

	var shopList []*selectrpc.ShopList
	for _, m := range shop {
		list := selectrpc.ShopList{
			Id:      int64(m.ID),
			Name:    m.Name,
			Price:   float32(m.Price),
			ClassId: m.ClassId,
			BrandId: m.BrandId,
		}
		shopList = append(shopList, &list)
	}
	return &selectrpc.ShopListResponse{
		List: shopList,
	}, nil
}
